'use client'

import { useState } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Progress } from '@/components/ui/progress'
import { Badge } from '@/components/ui/badge'
import {
  IconDatabase,
  IconUpload,
  IconCheck,
  IconX,
  IconRefresh,
  IconInfoCircle,
  IconAlertTriangle
} from '@tabler/icons-react'
import { toast } from 'sonner'
// 数据迁移将通过 API 路由执行

interface MigrationStep {
  id: string
  name: string
  description: string
  status: 'pending' | 'running' | 'completed' | 'error'
  progress: number
}

export default function DataMigrationPage() {
  const [isMigrating, setIsMigrating] = useState(false)
  const [migrationProgress, setMigrationProgress] = useState(0)
  const [migrationSteps, setMigrationSteps] = useState<MigrationStep[]>([
    {
      id: 'hospital',
      name: '医院基础数据',
      description: '迁移医院基本信息、配置等',
      status: 'pending',
      progress: 0
    },
    {
      id: 'departments',
      name: '科室数据',
      description: '迁移各科室信息、容量、负责人等',
      status: 'pending',
      progress: 0
    },
    {
      id: 'equipment',
      name: '设备数据',
      description: '迁移医疗设备信息、状态、维护记录等',
      status: 'pending',
      progress: 0
    },
    {
      id: 'alerts',
      name: '告警数据',
      description: '迁移系统告警、异常事件等',
      status: 'pending',
      progress: 0
    },
    {
      id: 'patient_flow',
      name: '患者流量数据',
      description: '迁移患者流量统计、趋势数据等',
      status: 'pending',
      progress: 0
    },
    {
      id: 'kpis',
      name: 'KPI指标数据',
      description: '迁移关键绩效指标、监控数据等',
      status: 'pending',
      progress: 0
    },
    {
      id: 'pois',
      name: 'POI点位数据',
      description: '迁移兴趣点、位置信息等',
      status: 'pending',
      progress: 0
    }
  ])

  const handleMigration = async () => {
    setIsMigrating(true)
    setMigrationProgress(0)

    // 重置所有步骤状态
    setMigrationSteps(prev => prev.map(step => ({
      ...step,
      status: 'pending',
      progress: 0
    })))

    try {
      toast.info('开始数据迁移...', {
        description: '正在将模拟数据迁移到 MongoDB 数据库'
      })

      // 模拟迁移过程
      for (let i = 0; i < migrationSteps.length; i++) {
        const step = migrationSteps[i]

        // 更新当前步骤状态
        setMigrationSteps(prev => prev.map((s, index) =>
          index === i
            ? { ...s, status: 'running', progress: 0 }
            : s
        ))

        // 模拟步骤执行
        for (let progress = 0; progress <= 100; progress += 10) {
          await new Promise(resolve => setTimeout(resolve, 100))

          setMigrationSteps(prev => prev.map((s, index) =>
            index === i
              ? { ...s, progress }
              : s
          ))

          setMigrationProgress((i * 100 + progress) / migrationSteps.length)
        }

        // 标记步骤完成
        setMigrationSteps(prev => prev.map((s, index) =>
          index === i
            ? { ...s, status: 'completed', progress: 100 }
            : s
        ))
      }

      // 执行实际的数据迁移（通过 API 路由）
      const response = await fetch('/api/migrate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      })

      if (!response.ok) {
        throw new Error('数据迁移失败')
      }

      const result = await response.json()
      if (!result.success) {
        throw new Error(result.error || '数据迁移失败')
      }

      toast.success('数据迁移完成！', {
        description: '所有模拟数据已成功迁移到 MongoDB 数据库'
      })

    } catch (error) {
      console.error('数据迁移失败:', error)
      toast.error('数据迁移失败', {
        description: error instanceof Error ? error.message : '未知错误'
      })
    } finally {
      setIsMigrating(false)
    }
  }

  const getStepIcon = (status: MigrationStep['status']) => {
    switch (status) {
      case 'completed':
        return <IconCheck className="w-5 h-5 text-green-500" />
      case 'running':
        return <IconRefresh className="w-5 h-5 text-blue-500 animate-spin" />
      case 'error':
        return <IconX className="w-5 h-5 text-red-500" />
      default:
        return <IconDatabase className="w-5 h-5 text-gray-400" />
    }
  }

  const getStepBadge = (status: MigrationStep['status']) => {
    switch (status) {
      case 'completed':
        return <Badge className="bg-green-500">已完成</Badge>
      case 'running':
        return <Badge className="bg-blue-500">进行中</Badge>
      case 'error':
        return <Badge className="bg-red-500">失败</Badge>
      default:
        return <Badge variant="secondary">等待中</Badge>
    }
  }

  return (
    <div className="container mx-auto p-6 max-w-4xl">
      <div className="mb-8">
        <h1 className="text-3xl font-bold mb-2">数据迁移管理</h1>
        <p className="text-gray-600">
          将可视化大屏的模拟数据迁移到 MongoDB 数据库中，实现数据的持久化存储
        </p>
      </div>

      {/* 迁移概览 */}
      <Card className="mb-6">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <IconDatabase className="w-5 h-5" />
            迁移概览
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <span className="text-sm font-medium">总体进度</span>
              <span className="text-sm text-gray-500">{Math.round(migrationProgress)}%</span>
            </div>
            <Progress value={migrationProgress} className="w-full" />

            <div className="grid grid-cols-3 gap-4 text-center">
              <div className="p-3 bg-green-50 rounded-lg">
                <div className="text-2xl font-bold text-green-600">
                  {migrationSteps.filter(s => s.status === 'completed').length}
                </div>
                <div className="text-sm text-green-600">已完成</div>
              </div>
              <div className="p-3 bg-blue-50 rounded-lg">
                <div className="text-2xl font-bold text-blue-600">
                  {migrationSteps.filter(s => s.status === 'running').length}
                </div>
                <div className="text-sm text-blue-600">进行中</div>
              </div>
              <div className="p-3 bg-gray-50 rounded-lg">
                <div className="text-2xl font-bold text-gray-600">
                  {migrationSteps.filter(s => s.status === 'pending').length}
                </div>
                <div className="text-sm text-gray-600">等待中</div>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 迁移步骤 */}
      <Card className="mb-6">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <IconUpload className="w-5 h-5" />
            迁移步骤
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {migrationSteps.map((step, index) => (
              <div key={step.id} className="flex items-center gap-4 p-4 border rounded-lg">
                <div className="flex-shrink-0">
                  {getStepIcon(step.status)}
                </div>
                <div className="flex-1">
                  <div className="flex items-center justify-between mb-2">
                    <h3 className="font-medium">{step.name}</h3>
                    {getStepBadge(step.status)}
                  </div>
                  <p className="text-sm text-gray-600 mb-2">{step.description}</p>
                  {step.status === 'running' && (
                    <Progress value={step.progress} className="w-full" />
                  )}
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* 操作按钮 */}
      <div className="flex gap-4">
        <Button
          onClick={handleMigration}
          disabled={isMigrating}
          className="flex items-center gap-2"
        >
          <IconUpload className="w-4 h-4" />
          {isMigrating ? '迁移中...' : '开始迁移'}
        </Button>

        <Button
          variant="outline"
          onClick={() => window.location.reload()}
          className="flex items-center gap-2"
        >
          <IconRefresh className="w-4 h-4" />
          刷新页面
        </Button>
      </div>

      {/* 信息提示 */}
      <Card className="mt-6">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <IconInfoCircle className="w-5 h-5" />
            迁移说明
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-3 text-sm text-gray-600">
            <div className="flex items-start gap-2">
              <IconAlertTriangle className="w-4 h-4 text-yellow-500 mt-0.5 flex-shrink-0" />
              <div>
                <strong>注意事项：</strong>
                <ul className="mt-1 space-y-1 ml-4">
                  <li>• 迁移过程会将现有模拟数据转换为数据库格式</li>
                  <li>• 数据将存储在你的 MongoDB 数据库中</li>
                  <li>• 迁移完成后，可视化大屏将从数据库读取数据</li>
                  <li>• 建议在迁移前备份重要数据</li>
                </ul>
              </div>
            </div>

            <div className="flex items-start gap-2">
              <IconDatabase className="w-4 h-4 text-blue-500 mt-0.5 flex-shrink-0" />
              <div>
                <strong>数据库信息：</strong>
                <ul className="mt-1 space-y-1 ml-4">
                  <li>• 数据库：medical_digital_twin</li>
                  <li>• 集合：hospitals, departments, equipment, alerts, patient_flow, kpis, pois</li>
                  <li>• 连接：mongodb+srv://1191665779:20020219aa@zn.apmsejq.mongodb.net/</li>
                </ul>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
